/**
 * @file test_threads.c
 * @brief 线程功能测试
 */

#include "action_camera.h"
#include <assert.h>

// 测试线程创建和管理
void test_thread_management(void) {
    printf("Testing thread management...\n");
    
    // 初始化系统
    assert(system_init() == 0);
    
    // 启动系统
    assert(system_start() == 0);
    
    // 检查线程状态
    assert(g_camera_system.threads[THREAD_CAMERA].status == THREAD_RUNNING);
    assert(g_camera_system.threads[THREAD_ENCODER].status == THREAD_RUNNING);
    assert(g_camera_system.threads[THREAD_STORAGE].status == THREAD_RUNNING);
    assert(g_camera_system.threads[THREAD_UI].status == THREAD_RUNNING);
    assert(g_camera_system.threads[THREAD_MONITOR].status == THREAD_RUNNING);
    
    // 检查活动线程数
    assert(atomic_load(&g_camera_system.sync.active_threads) >= 5);
    
    printf("Thread management test passed\n");
}

// 测试线程间通信
void test_thread_communication(void) {
    printf("Testing thread communication...\n");
    
    // 发送测试消息到相机线程
    message_t test_msg = {
        .type = MSG_CONTROL,
        .timestamp = get_system_timestamp(),
        .source_thread = THREAD_MAIN,
        .dest_thread = THREAD_CAMERA,
        .data_size = 12
    };
    strcpy((char*)test_msg.data, "test_msg");
    
    assert(message_queue_send(&g_camera_system.message_queues[THREAD_CAMERA], 
                            &test_msg) == 0);
    
    printf("Thread communication test passed\n");
}

// 测试系统关闭流程
void test_system_shutdown(void) {
    printf("Testing system shutdown...\n");
    
    // 发送关闭消息
    message_t shutdown_msg = {
        .type = MSG_SHUTDOWN,
        .timestamp = get_system_timestamp(),
        .source_thread = THREAD_MAIN,
        .dest_thread = THREAD_MAIN,
        .data_size = 0
    };
    
    assert(message_queue_send(&g_camera_system.message_queues[THREAD_MAIN], 
                            &shutdown_msg) == 0);
    
    // 等待系统关闭
    usleep(500000); // 500ms
    
    printf("System shutdown test passed\n");
}

int main(void) {
    printf("=== Action Camera Thread Tests ===\n");
    
    // 运行线程管理测试
    test_thread_management();
    
    // 运行通信测试
    test_thread_communication();
    
    // 运行关闭测试
    test_system_shutdown();
    
    // 清理系统
    system_cleanup();
    
    printf("=== All Thread Tests Passed ===\n");
    return 0;
}